﻿using Apewer;
using Apewer.Internals;
using Apewer.Source;
using Apewer.Web;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Text;
using System.Collections.Specialized;

#if !NET20
using System.Dynamic;
#endif

/// <summary>扩展方法。</summary>
public static class Extensions
{

    /// <summary>是 NULL 值，或是 DBNULL 值。</summary>
    public static bool IsNull(this object @this) => @this == null || @this.Equals(DBNull.Value);

    /// <summary>不是 NULL 值，且不是 DBNULL 值。</summary>
    public static bool NotNull(this object @this) => @this != null && !@this.Equals(DBNull.Value);

    /// <summary>是默认值。</summary>
    public static bool IsDefault(this object @this) => RuntimeUtility.IsDefault(@this);

    #region Class

    /// <summary>用 <see cref="Apewer.Class{T}"/> 装箱。</summary>
    public static Class<T> Class<T>(this T value) => new Class<T>(value);

    #endregion

    #region Class Utility

    /// <summary>调用 Get 方法。</summary>
    public static object Get(this PropertyInfo @this, object instance) => RuntimeUtility.InvokeGet<object>(instance, @this);

    /// <summary>调用 Set 方法。</summary>
    public static void Set(this PropertyInfo @this, object instance, object value) => RuntimeUtility.InvokeSet<object>(instance, @this, value);

    /// <summary>调用 Get 方法。</summary>
    public static T Get<T>(this PropertyInfo @this, object instance) => RuntimeUtility.InvokeGet<T>(instance, @this);

    /// <summary>调用 Set 方法。</summary>
    public static void Set<T>(this PropertyInfo @this, object instance, T value) => RuntimeUtility.InvokeSet<T>(instance, @this, value);

    /// <summary>判断静态属性。</summary>
    public static bool IsStatic(this PropertyInfo @this) => RuntimeUtility.IsStatic(@this);

    /// <summary>以安全的方式获取消息内容，对无效的 Exception 返回 NULL 值。</summary>
    public static string Message(this Exception ex) => RuntimeUtility.Message(ex);

#if NET20

    /// <summary>为指定对象设置属性值。</summary>
    /// <param name="property">属性。</param>
    /// <param name="obj">要设置属性的对象。</param>
    /// <param name="value">属性值。</param>
    /// <exception cref="ArgumentNullException"></exception>
    public static void SetValue(this PropertyInfo property, object obj, object value)
    {
        if (property == null) throw new ArgumentNullException(nameof(property));
        property.SetValue(obj, value, null);
    }

#endif

    #endregion

    #region Dynamic

#if !NET20

    /// <summary>转换 <see cref="ObjectSet{T}"/> 到 <see cref="ExpandoObject"/> 对象。</summary>
    public static ExpandoObject Expando<T>(this ObjectSet<T> os) => ObjectSet<T>.Expando(os);

    /// <summary>转换 <see cref="ObjectSet{T}"/> 数组到 <see cref="ExpandoObject"/> 数组。</summary>
    public static ExpandoObject[] Expando<T>(this ObjectSet<T>[] oss) => ObjectSet<T>.Expando(oss);

    /// <summary>设置 <see cref="ObjectSet{T}"/> 的 Always 属性，对动态属性的访问始终返回 TRUE 值。</summary>
    public static void SetAlways<T>(this ObjectSet<T> os, bool always) => os._always = always;

#endif

    #endregion

    #region Number

    /// <summary>判断此值为零。</summary>
    public static bool IsZero(this decimal @this) => @this.Equals(0M);

    /// <summary>判断此值为零。</summary>
    public static bool IsZero(this double @this) => @this.Equals(0D);

    /// <summary>判断此值为零。</summary>
    public static bool IsZero(this float @this) => @this.Equals(0F);

    /// <summary>判断此值非零。</summary>
    public static bool NotZero(this decimal @this) => !@this.Equals(0M);

    /// <summary>判断此值非零。</summary>
    public static bool NotZero(this double @this) => !@this.Equals(0D);

    /// <summary>判断此值非零。</summary>
    public static bool NotZero(this float @this) => !@this.Equals(0F);

    /// <summary>约束值范围，若源值不在范围中，则修改为接近的值。</summary>
    public static T Restrict<T>(this T @this, T min, T max) where T : IComparable => NumberUtility.Restrict(@this, min, max);

    #endregion

    #region String、StringBuilder

    /// <summary>转换文本为驼峰形式。</summary>
    public static string Camel(this string @this) => TextUtility.Camel(@this);

    /// <summary>转换为 Boolean 值。</summary>
    public static bool Boolean(this string @this) => NumberUtility.Boolean(@this);

    /// <summary>转换为 Byte 值。</summary>
    public static byte Byte(this string @this) => NumberUtility.Byte(@this);

    /// <summary>转换为 Int32 值。</summary>
    public static int Int32(this string @this) => NumberUtility.Int32(@this);

    /// <summary>转换为 Int64 值。</summary>
    public static long Int64(this string @this) => NumberUtility.Int64(@this);

    /// <summary>转换为 Decimal 值。</summary>
    public static decimal Decimal(this string @this) => NumberUtility.Decimal(@this);

    /// <summary>转换为单精度浮点值。</summary>
    public static float Float(this string @this) => NumberUtility.Float(@this);

    /// <summary>转换为双精度浮点值。</summary>
    public static double Double(this string @this) => NumberUtility.Double(@this);

    /// <summary>将文本转换为字节数组，默认使用 UTF-8。</summary>
    public static byte[] Bytes(this string @this, Encoding encoding = null) => TextUtility.Bytes(@this, encoding);

    /// <summary>验证字符串为 NULL、为空或仅含空白。</summary>
    public static bool IsEmpty(this string @this) => TextUtility.IsEmpty(@this);

    /// <summary>验证字符串为 NULL、为空或仅含空白。</summary>
    public static bool NotEmpty(this string @this) => TextUtility.NotEmpty(@this);

    /// <summary>验证字符串为 NULL、为空或无实际内容。</summary>
    public static bool IsBlank(this string @this) => TextUtility.IsBlank(@this);

    /// <summary>验证字符串含有实际内容。</summary>
    public static bool NotBlank(this string @this) => TextUtility.NotBlank(@this);

    /// <summary>用指定的分隔符拆分文本。</summary>
    public static string[] Split(this string @this, string separator) => TextUtility.Split(@this, separator);

    /// <summary>使用多个分隔符切分字符串，得到多个子字符串。</summary>
    public static string[] Split(this string @this, params char[] separators) => TextUtility.Split(@this, separators);

    /// <summary>返回此字符串的安全键副本。</summary>
    public static string SafeKey(this string @this, int maxLength = 255) => TextUtility.SafeKey(@this, maxLength);

    /// <summary>移除字符串前后的空字符。</summary>
    /// <remarks>trimBlank：移除空格、全角空格、换行符、回车符、制表符和换页符。</remarks>
    public static string Trim(this string @this, bool trimBlank = false) => TextUtility.Trim(@this, trimBlank);

    /// <summary>移除字符串前后的空字符。</summary>
    /// <remarks>trimBlank：移除空格、全角空格、换行符、回车符、制表符和换页符。</remarks>
    public static string ToTrim(this string @this, bool trimBlank = false) => TextUtility.Trim(@this, trimBlank);

    /// <summary>返回此字符串转换为小写形式的副本。</summary>
    public static string Lower(this string @this) => TextUtility.Lower(@this);

    /// <summary>返回此字符串转换为大写形式的副本。</summary>
    public static string Upper(this string @this) => TextUtility.Upper(@this);

    /// <summary>追加字符串。</summary>
    public static string Append(this string @this, params object[] text) => TextUtility.Merge(@this, TextUtility.Merge(text));

    /// <summary>追加文本。</summary>
    public static void Append(this StringBuilder @this, params object[] text) => TextUtility.Append(@this, text);

    /// <summary>防注入处理，去除会引发代码注入的字符。可限定字符串长度。</summary>
    public static string AntiInject(this string @this, int length = -1, string blacklist = null) => TextUtility.AntiInject(@this, length, blacklist);

    /// <summary>将 Base64 字符串转换为字节数组。</summary>
    public static byte[] Base64(this string text) => BytesUtility.FromBase64(text);

    /// <summary>对 URL 编码。</summary>
    public static string EncodeUrl(this string @this) => UrlEncoding.Encode(@this);

    /// <summary>对 URL 解码。</summary>
    public static string DecodeUrl(this string @this) => UrlEncoding.Decode(@this);

    /// <summary>获取指定长度的字符串片段，可指定 trim 参数对片段再次修剪。</summary>
    public static string Left(this string text, int maxLength, bool trim = false) => TextUtility.Left(text, maxLength, trim);

    /// <summary>获取指定长度的字符串片段，可指定 trim 参数对片段再次修剪。</summary>
    public static string Right(this string text, int maxLength, bool trim = false) => TextUtility.Right(text, maxLength, trim);

    /// <summary>剪取文本内容，若指定头部为空则从原文本首部起，若指定尾部为空则至原文本末尾。</summary>
    /// <returns>剪取后的内容，不包含 head 和 foot。</returns>
    public static string Cut(this string text, string head = null, string foot = null) => TextUtility.Cut(text, head, foot);

    /// <summary>约束字符串中的字符，只包含指定的字符。</summary>
    public static string Restrict(this string text, char[] chars) => TextUtility.Restrict(text, chars);

    /// <summary>约束字符串中的字符，只包含指定的字符。</summary>
    public static string Restrict(this string text, string chars) => TextUtility.Restrict(text, chars);

    /// <summary>连接字符串。</summary>
    public static string Join(this IEnumerable<string> strings, string separator) => TextUtility.Join(separator, strings);

    #endregion

    #region Byte[]

    /// <summary>将字节数组转换为 Base64 字符串。</summary>
    public static string Base64(this byte[] @this) => BytesUtility.ToBase64(@this);

    /// <summary>将字节数组转换为文本，默认为 UTF-8。</summary>
    public static string Text(this byte[] @this, Encoding encoding = null) => TextUtility.FromBytes(@this, encoding);

    /// <summary>检查字节数组是 UTF-8 文本，默认最多检测 1MB 数据（指定为 0 将不限制检查长度）。</summary>
    public static bool IsUTF8(this byte[] @this, int checkLength = 1048576) => TextUtility.IsUTF8(@this, checkLength, null);

    /// <summary>检查字节数组包含 UTF-8 BOM 头。</summary>
    public static bool ContainsBOM(this byte[] @this) => TextUtility.ContainsBOM(@this);

    #endregion

    #region DateTime

    /// <summary>获取毫秒时间戳。当指定了 <see cref="ClockUtility.CustomToStamp"/> 时将优先使用自定义的方法。</summary>
    /// <remarks>默认不判断参数的时区，与 <see cref="DateTimeKind.Unspecified"/> 相同。</remarks>
    public static long Stamp(this DateTime dt) => ClockUtility.ToStamp(dt);

    /// <summary>转换为易于阅读的文本。</summary>
    /// <remarks>格式：1970-01-01 00:00:00.000</remarks>
    public static string Lucid(this DateTime @this, bool date = true, bool time = true, bool seconds = true, bool milliseconds = true) => ClockUtility.Lucid(@this, date, time, seconds, milliseconds);

    /// <summary>转换为紧凑的文本。</summary>
    public static string Compact(this DateTime @this, bool date = true, bool time = true, bool seconds = true, bool milliseconds = true) => ClockUtility.Compact(@this, date, time, seconds, milliseconds);

    /// <summary>当前 DateTime 为闰年。</summary>
    public static bool LeapYear(this DateTime @this) => ClockUtility.IsLeapYear(@this);

    /// <summary>解析毫秒时间戳，获取 DateTime 对象。当指定了 <see cref="ClockUtility.CustomFromStamp"/> 时将优先使用自定义的方法。</summary>
    /// <remarks>默认不判断系统时区，返回的结果是 <see cref="DateTimeKind.Unspecified"/>。</remarks>
    /// <exception cref="ArgumentOutOfRangeException"></exception>
    public static DateTime DateTime(this long stamp) => ClockUtility.FromStamp(stamp);

    #region Nullable

    /// <summary>转换为易于阅读的文本。</summary>
    /// <remarks>格式：1970-01-01 00:00:00.000</remarks>
    public static string Lucid(this DateTime? @this, bool date = true, bool time = true, bool seconds = true, bool milliseconds = true) => @this == null ? default : ClockUtility.Lucid(@this.Value, date, time, seconds, milliseconds);

    /// <summary>转换为紧凑的文本。</summary>
    public static string Compact(this DateTime? @this, bool date = true, bool time = true, bool seconds = true, bool milliseconds = true) => @this == null ? default : ClockUtility.Compact(@this.Value, date, time, seconds, milliseconds);

    /// <summary>获取毫秒时间戳。当指定了 <see cref="ClockUtility.CustomToStamp"/> 时将优先使用自定义的方法。</summary>
    /// <remarks>默认不判断参数的时区，与 <see cref="DateTimeKind.Unspecified"/> 相同。</remarks>
    public static long Stamp(this DateTime? @this) => @this == null ? default : ClockUtility.ToStamp(@this.Value);

    /// <summary>转换为易于阅读的文本。</summary>
    /// <remarks>格式：1970-01-01 00:00:00.000</remarks>
    public static string Lucid(this Class<DateTime> @this, bool date = true, bool time = true, bool seconds = true, bool milliseconds = true) => @this == null ? default : ClockUtility.Lucid(@this.Value, date, time, seconds, milliseconds);

    /// <summary>转换为紧凑的文本。</summary>
    public static string Compact(this Class<DateTime> @this, bool date = true, bool time = true, bool seconds = true, bool milliseconds = true) => @this == null ? default : ClockUtility.Compact(@this.Value, date, time, seconds, milliseconds);

    /// <summary>获取毫秒时间戳。</summary>
    public static long Stamp(this Class<DateTime> @this) => @this == null ? default : ClockUtility.ToStamp(@this.Value);

    #endregion

    #endregion

    #region ArrayBuilder

    /// <summary>拼接 <see cref="char"/> 为字符串。</summary>
    /// <returns>连接后的字符串，返回值不为 NULL。</returns>
    public static string Text(this ArrayBuilder<char> ab) => ArrayBuilder<char>.Text(ab);

    /// <summary>拼接 <see cref="char"/> 为字符串。</summary>
    /// <returns>连接后的字符串，返回值不为 NULL。</returns>
    /// <exception cref="ArgumentOutOfRangeException"></exception>
    public static string Text(this ArrayBuilder<char> ab, int start, int count) => ArrayBuilder<char>.Text(ab, start, count);

    /// <summary>使用指定的分隔符连接 <see cref="ArrayBuilder{T}"/> 中的元素，指定分隔符为 NULL 将忽略分隔符。</summary>
    /// <returns>连接后的字符串，返回值不为 NULL。</returns>
    public static string Join(this ArrayBuilder<string> ab, string separator = null) => ArrayBuilder<string>.Join(ab, separator);

    /// <summary>使用指定的分隔符连接 <see cref="ArrayBuilder{T}"/> 中的元素，指定分隔符为 NULL 将忽略分隔符。</summary>
    /// <returns>连接后的字符串，返回值不为 NULL。</returns>
    /// <exception cref="ArgumentOutOfRangeException"></exception>
    public static string Join(this ArrayBuilder<string> ab, string separator, int startIndex, int maxCount) => ArrayBuilder<string>.Join(ab, separator, startIndex, maxCount);

    #endregion

    #region Json

    /// <summary>Json 对象可用。</summary>
    public static bool Available(this Json @this) => @this != null && @this.Available;

    /// <summary>生成 JSON 对象，失败时返回 NULL。</summary>
    /// <param name="this">将要解析的对象。</param>
    /// <param name="lowerCase">在 Json 中将属性名称转换为小写。</param>
    /// <param name="depth">解析深度。</param>
    /// <param name="force">强制解析所有属性，忽略 Serializable 特性。</param>
    public static Json Json(this IDictionary @this, bool lowerCase = false, int depth = -1, bool force = false) => Apewer.Json.From(@this, lowerCase, depth, force);

    /// <summary>解析实现 IList 的对象为 Json 对象，失败时返回 Null。</summary>
    /// <param name="this">将要解析的对象。</param>
    /// <param name="lowerCase">在 Json 中将属性名称转换为小写。</param>
    /// <param name="depth">解析深度。</param>
    /// <param name="force">强制解析所有属性，忽略 Serializable 特性。</param>
    public static Json Json(this IList @this, bool lowerCase = false, int depth = -1, bool force = false) => Apewer.Json.From(@this, lowerCase, depth, force);

    /// <summary>
    /// <para>解析对象为 Json 对象，包含所有公共属性，失败时返回 Null。</para>
    /// <para>String 对象将解析文本；Json 对象将返回实例；String 对象将解析文本；实现 IDictionary 或 IList 的对象将解析内容。</para>
    /// </summary>
    /// <param name="this">将要解析的对象。</param>
    /// <param name="lowerCase">在 Json 中将属性名称转换为小写。</param>
    /// <param name="depth">解析深度。</param>
    /// <param name="force">强制解析所有属性，忽略 Serializable 特性。</param>
    /// <exception cref="System.Exception"></exception>
    public static Json Json(object @this, bool lowerCase = false, int depth = -1, bool force = false) => Apewer.Json.From(@this, lowerCase, depth, force);

    /// <summary>填充类型实例，失败时返回 NULL 值。</summary>
    /// <param name="this">将要解析的对象。</param>
    /// <param name="ignoreCase">忽略属性名称大小写。</param>
    /// <param name="ignoreChars">忽略的属性名称字符。</param>
    /// <param name="force">强制填充，忽略 <typeparamref name="T"/> 的 Serializable 特性。</param>
    public static T Object<T>(this Json @this, bool ignoreCase = true, string ignoreChars = null, bool force = false) where T : class, new() => Apewer.Json.Object<T>(@this, ignoreCase, ignoreChars, force);

    /// <summary>填充类型实例，失败时返回 NULL 值。</summary>
    /// <param name="this">将要解析的对象。</param>
    /// <param name="ignoreCase">忽略属性名称大小写。</param>
    /// <param name="ignoreChars">忽略的属性名称字符。</param>
    /// <param name="force">强制填充，忽略 <typeparamref name="T"/> 的 Serializable 特性。</param>
    public static T[] Array<T>(this Json @this, bool ignoreCase = true, string ignoreChars = null, bool force = false) => Apewer.Json.Array<T>(@this, ignoreCase, ignoreChars, force);

    /// <summary>设置属性名称为小写。</summary>
    public static Json Lower(this Json @this) => Apewer.Json.Lower(@this);

    /// <summary>设置属性名称为驼峰形式。</summary>
    public static Json Camel(this Json @this) => Apewer.Json.Camel(@this);

    #endregion

    #region Logger

    /// <summary>记录文本。多个 Content 参数将以“ | ”分隔。</summary>
    public static void Write(this Logger logger, params object[] content) => logger?.Output(null, content, null);

    /// <summary>记录异常。</summary>
    public static void Exception<T>(this Logger logger, T exception, params object[] content) where T : Exception => logger?.Output("Exception", content, exception);

    /// <summary>记录错误。多个 Content 参数将以“ | ”分隔。</summary>
    public static void Error(this Logger logger, params object[] content) => logger?.Output("Error", content, null);

    /// <summary>记录警告。多个 Content 参数将以“ | ”分隔。</summary>
    public static void Warning(this Logger logger, params object[] content) => logger?.Output("Warning", content, null);

    /// <summary>记录警告。多个 Content 参数将以“ | ”分隔。</summary>
    public static void Info(this Logger logger, params object[] content) => logger?.Output("Info", content, null);

    /// <summary>记录文本。多个 Content 参数将以“ | ”分隔。</summary>
    public static void Text(this Logger logger, params object[] content) => logger?.Output(null, content, null);

    /// <summary>记录调试。多个 Content 参数将以“ | ”分隔。</summary>
    [Conditional("DEBUG")]
    public static void Debug(this Logger logger, params object[] content) => logger?.Output("Debug", content, null);

    #endregion

    #region Stream

    /// <summary>重置流的位置到开始位置。</summary>
    public static bool ResetPosition(this Stream @this) => BytesUtility.ResetPosition(@this);

    /// <summary>读取源流中的数据，并将数据写入目标流，获取写入的字节数。</summary>
    public static long Read(this Stream @this, Stream destination, Action<long> progress = null) => BytesUtility.Read(@this, destination, progress);

    /// <summary>读取源流中的数据，并将数据写入目标流，获取写入的字节数。</summary>
    public static long Read(this Stream @this, Stream destination, Func<long, bool> progress) => BytesUtility.Read(@this, destination, progress);

    /// <summary>读取源流中的数据，获取写入的字节。</summary>
    public static byte[] Read(this Stream @this, bool dispose) => BytesUtility.Read(@this, 1024, dispose);

    /// <summary>读取源流中的数据。</summary>
    public static byte[] Read(this Stream @this, int buffer = 1024, bool dispose = false) => BytesUtility.Read(@this, buffer, dispose);

    /// <summary>向流写入数据。</summary>
    ///  <param name="this">源流。</param>
    ///  <param name="bytes">要写入的数据。</param>
    public static long Write(this Stream @this, params byte[] bytes) => BytesUtility.Write(@this, bytes);

    /// <summary>读取源流中的数据，并将数据写入当前流，获取写入的字节数。</summary>
    /// <param name="this">目标流。</param>
    /// <param name="source">源流。</param>
    public static long Write(this Stream @this, Stream source) => BytesUtility.Read(source, @this);

    /// <summary>获取 MD5 值。</summary>
    public static byte[] MD5(this Stream @this) => BytesUtility.MD5(@this);

    /// <summary>获取 SHA1 值。</summary>
    public static byte[] SHA1(this Stream @this) => BytesUtility.SHA1(@this);

#if !NET20

    /// <summary>获取 SHA256 值。</summary>
    public static byte[] SHA256(this Stream @this) => BytesUtility.SHA256(@this);

#endif

    #endregion

    #region Rrflection

    /// <summary>判断指定类型具有特性。</summary>
    public static bool Contains<T>(this ICustomAttributeProvider @this, bool inherit = false) where T : Attribute => RuntimeUtility.Contains<T>(@this, inherit);

    #endregion

    #region Collection

    /// <summary>添加多个元素。</summary>
    public static void Add<T>(this List<T> @this, params T[] items)
    {
        if (@this != null && items != null) @this.AddRange(items);
    }

    /// <summary>添加元素。</summary>
    public static bool Add<TKey, TValue>(this IList<KeyValuePair<TKey, TValue>> @this, TKey key, TValue value) => CollectionUtility.Add<TKey, TValue>(@this, key, value);

    /// <summary>判断集合为空。</summary>
    public static bool IsEmpty<T>(this IEnumerable<T> @this) => CollectionUtility.IsEmpty(@this);

    /// <summary>判断集合存在元素。</summary>
    public static bool NotEmpty<T>(this IEnumerable<T> @this) => CollectionUtility.NotEmpty(@this);

    /// <summary>检查集合是否包含 item。</summary>
    public static bool Contains<T>(this IEnumerable<T> @this, T item) => CollectionUtility.Contains(@this, item);

    /// <summary>获取 item 在集合中的偏移位置，不存在时返回 -1。</summary>
    public static int IndexOf<T>(this IEnumerable<T> objects, T item) => CollectionUtility.IndexOf(objects, item);

    /// <summary>获取集合中元素的数量。</summary>
    public static int Count<T>(this IEnumerable<T> @this) => CollectionUtility.Count(@this);

    /// <summary>获取可枚举集合的部分元素。</summary>
    public static T[] Slice<T>(this IEnumerable<T> @this, int start = 0, int count = -1, Func<T> stuffer = null) => CollectionUtility.Slice<T>(@this, start, count, stuffer);

    /// <summary>安全转换为 List&lt;<typeparamref name="T"/>&gt; 对象。可指定排除 NULL 值元素。</summary>
    public static List<T> List<T>(this IEnumerable<T> @this, bool excludeNull = false) => CollectionUtility.List<T>(@this, excludeNull);

    /// <summary>安全转换为 &lt;<typeparamref name="T"/>&gt;[] 对象。可指定排除 NULL 值元素。</summary>
    public static T[] Array<T>(IEnumerable<T> @this, bool excludeNull = false) => CollectionUtility.Array<T>(@this, excludeNull);

    /// <summary>对列表中的元素排序。</summary>
    public static List<T> Sort<T>(this List<T> @this, Func<T, T, int> comparison) => CollectionUtility.Sort(@this, comparison);

    /// <summary>对字典中的键排序。</summary>
    public static Dictionary<TKey, TValue> SortKey<TKey, TValue>(this Dictionary<TKey, TValue> @this, Func<TKey, TKey, int> comparison) => CollectionUtility.SortKey(@this, comparison);

    /// <summary>对字典中的键排序。</summary>
    public static Dictionary<TKey, TValue> SortKey<TKey, TValue>(this Dictionary<TKey, TValue> @this) where TKey : IComparable<TKey> => CollectionUtility.SortKey(@this, (a, b) => a.CompareTo(b));

    /// <summary>对字典中的值排序。</summary>
    public static Dictionary<TKey, TValue> SortValue<TKey, TValue>(this Dictionary<TKey, TValue> @this, Func<TValue, TValue, int> comparison) => CollectionUtility.SortValue(@this, comparison);

    /// <summary>对字典中的值排序。</summary>
    public static Dictionary<TKey, TValue> SortValue<TKey, TValue>(this Dictionary<TKey, TValue> @this) where TValue : IComparable<TValue> => CollectionUtility.SortValue(@this, (a, b) => a.CompareTo(b));

    /// <summary>获取集合中的第一个元素。可指定失败时的默认返回值。</summary>
    public static T First<T>(this IEnumerable<T> collection, T failed = default(T)) => CollectionUtility.First(collection, failed);

    /// <summary>获取集合中的最后一个元素。可指定失败时的默认返回值。</summary>
    public static T Last<T>(this IEnumerable<T> collection, T failed = default(T)) => CollectionUtility.Last(collection, failed);

    /// <summary>生成 StringPairs 对象实例为副本。</summary>
    public static StringPairs StringPairs(this NameValueCollection @this) => Apewer.StringPairs.From(@this);

    /// <summary>对数组排序。</summary>
    /// <exception cref="NullReferenceException"></exception>
    public static void Sort<T>(this T[] @this, Func<T, T, int> func) { if (@this != null && func != null) System.Array.Sort(@this, new Comparison<T>(func)); }

    /// <summary>对数组升序排序。</summary>
    /// <exception cref="NullReferenceException"></exception>
    public static void Ascend<T>(this T[] @this) where T : IComparable<T> { if (@this != null) Sort(@this, (a, b) => a.CompareTo(b)); }

    /// <summary>对数组升序排序。</summary>
    /// <exception cref="NullReferenceException"></exception>
    public static void Ascend<T, TProp>(this T[] @this, Func<T, TProp> func) where TProp : IComparable<TProp> { if (@this != null && func != null) Sort(@this, (a, b) => func(a).CompareTo(func(b))); }

    /// <summary>对数组降序排序。</summary>
    /// <exception cref="NullReferenceException"></exception>
    public static void Descend<T>(this T[] @this) where T : IComparable<T> { if (@this != null) Sort(@this, (a, b) => 0 - a.CompareTo(b)); }

    /// <summary>对数组降序排序。</summary>
    /// <exception cref="NullReferenceException"></exception>
    public static void Descend<T, TProp>(this T[] @this, Func<T, TProp> func) where TProp : IComparable<TProp> { if (@this != null && func != null) Sort(@this, (a, b) => 0 - func(a).CompareTo(func(b))); }

    #endregion

    #region Sets

    /// <summary>解析源对象。</summary>
    public static Dictionary<string, object> Origin(this ObjectSet instance) => instance == null ? null : instance.Origin;

    /// <summary>解析源对象。</summary>
    public static Dictionary<string, T> Origin<T>(this ObjectSet<T> instance) => instance == null ? null : instance.Origin;

    /// <summary>清空元素。</summary>
    public static void Clear(this ObjectSet instance) => instance?.Origin?.Clear();

    /// <summary>解析源对象。</summary>
    public static Dictionary<string, string> Origin(this TextSet instance) => instance == null ? null : instance.Origin;

    /// <summary>清空元素。</summary>
    public static void Clear(this TextSet instance) => instance?.Origin?.Clear();

    #endregion

    #region Source

    /// <summary>获取默认表中指定单元格的内容。从第 0 行第 0 列开始。</summary>
    public static Class<DateTime> DateTime(this IQuery @this, int row, int column) => @this == null ? null : ClockUtility.DateTime(@this.Value(row, column));

    /// <summary>获取默认表中指定单元格的内容。从第 0 行开始。</summary>
    public static Class<DateTime> DateTime(this IQuery @this, int row, string column) => @this == null ? null : ClockUtility.DateTime(@this.Value(row, column));

    /// <summary>获取默认表中指定单元格的内容。从第 0 行第 0 列开始。</summary>
    public static Int32 Int32(this IQuery @this, int row, int column) => @this == null ? 0 : NumberUtility.Int32(@this.Value(row, column));

    /// <summary>获取默认表中指定单元格的内容。从第 0 行开始。</summary>
    public static Int32 Int32(this IQuery @this, int row, string column) => @this == null ? 0 : NumberUtility.Int32(@this.Value(row, column));

    /// <summary>获取默认表中指定单元格的内容。从第 0 行第 0 列开始。</summary>
    public static Int64 Int64(this IQuery @this, int row, int column) => @this == null ? 0L : NumberUtility.Int64(@this.Value(row, column));

    /// <summary>获取默认表中指定单元格的内容。从第 0 行开始。</summary>
    public static Int64 Int64(this IQuery @this, int row, string column) => @this == null ? 0L : NumberUtility.Int64(@this.Value(row, column));

    /// <summary>获取默认表中指定单元格的内容。从第 0 行第 0 列开始。</summary>
    public static Decimal Decimal(this IQuery @this, int row, int column) => @this == null ? 0M : NumberUtility.Decimal(@this.Value(row, column));

    /// <summary>获取默认表中指定单元格的内容。从第 0 行开始。</summary>
    public static Decimal Decimal(this IQuery @this, int row, string column) => @this == null ? 0M : NumberUtility.Decimal(@this.Value(row, column));

    /// <summary>获取默认表中指定单元格的内容。从第 0 行第 0 列开始。</summary>>
    public static Double Double(this IQuery @this, int row, int column) => @this == null ? 0D : NumberUtility.Double(@this.Value(row, column));

    /// <summary>获取默认表中指定单元格的内容。从第 0 行开始。</summary>>
    public static Double Double(this IQuery @this, int row, string column) => @this == null ? 0D : NumberUtility.Double(@this.Value(row, column));

    /// <summary>获取默认表中指定单元格的内容。从第 0 行第 0 列开始。</summary>
    public static string Text(this IQuery @this, int row, int column) => @this == null ? null : TextUtility.Text(@this.Value(row, column));

    /// <summary>获取默认表中指定单元格的内容。从第 0 行开始。</summary>
    public static string Text(this IQuery @this, int row, string column) => @this == null ? null : TextUtility.Text(@this.Value(row, column));

    /// <summary>转换 <see cref="System.Data.DataTable"/> 到 <see cref="ObjectSet{T}"/> 数组，每行记录为一个 ObjectSet 对象。</summary>
    /// <returns>当参数 table 无效时返回 0 长度的 <see cref="ObjectSet{T}"/> 数组。</returns>
    public static ObjectSet[] ObjectSet(this IQuery @this) => @this == null ? null : SourceUtility.ObjectSet(@this.Table);

    /// <summary>转换 <see cref="DataTable"/> 为 CSV 文本，不存在表时返回 NULL 值。可指定是否包含表头。</summary>
    public static string Csv(this IQuery query, bool withHead = false) => query == null ? null : SourceUtility.Csv(query.Table, withHead);

    #endregion

    #region Web

    /// <summary>获取参数，指定可能的参数名，默认将修剪参数值。</summary>
    /// <remarks>当从 URL 中获取参数时将解码。</remarks>
    public static string Parameter(this ApiRequest @this, params string[] names) => ApiUtility.Parameter(@this, true, names);

    /// <summary>设置 status 为 error，并设置 message 的内容。</summary>
    public static void Error(this ApiResponse @this, string message = "未知错误。") => ApiUtility.Error(@this, message);

    /// <summary>输出字节数组。</summary>
    public static void Bytes(this ApiResponse @this, byte[] bytes, string type = "application/octet-stream") => ApiUtility.Model(@this, new ApiBytesModel(bytes, type));

    /// <summary>输出 UTF-8 文本。</summary>
    public static void Text(this ApiResponse @this, string text, string contentType = "text/plain") => ApiUtility.Model(@this, new ApiTextModel(text, contentType));

    /// <summary>输出 Json 文本。</summary>
    public static void Json(this ApiResponse @this, Json json, bool indented = false, bool camel = true) => ApiUtility.Model(@this, new ApiJsonModel(json, indented, camel));

    /// <summary>输出文件。</summary>
    public static void File(this ApiResponse @this, string path) => ApiUtility.Model(@this, new ApiFileModel(path));

    /// <summary>重定向。</summary>
    public static void Redirect(this ApiResponse @this, string location) => ApiUtility.Model(@this, new ApiRedirectModel(location));

    #endregion

}


